#!/bin/sh
#
# Perform necessary datadog-agent setup steps after package is installed.
#
# .deb: STEP 5 of 5

INSTALL_DIR=/opt/datadog-agent
LOG_DIR=/var/log/datadog
CONFIG_DIR=/etc/datadog-agent
SERVICE_NAME=datadog-agent

# If we are inside the Docker container, do nothing
if [ -n "$DOCKER_DD_AGENT" ]; then
    echo "Installation from docker-dd-agent, nothing to do in postinst"
    exit 0
fi

set -e
case "$1" in
    configure)
        # Only create dd-agent group and/or user if they don't already exist
        getent group dd-agent >/dev/null || (echo "Creating dd-agent group" && addgroup --system dd-agent --quiet)
        set +e
        id -u dd-agent >/dev/null 2>&1
        USER_EXISTS=$?
        set -e
        if [ ! $USER_EXISTS -eq 0 ]; then
            echo "Creating dd-agent user"
            adduser --system dd-agent --disabled-login --shell /usr/sbin/nologin --home ${INSTALL_DIR} --no-create-home --group --quiet
        elif id -nG dd-agent | grep --invert-match --word-regexp --quiet 'dd-agent'; then
            # User exists but is not part of the dd-agent group
            echo "Adding dd-agent user to dd-agent group"
            usermod -g dd-agent dd-agent
        fi

        # Create a symlink to the agent's binary
        ln -sf $INSTALL_DIR/bin/agent/agent /usr/bin/datadog-agent
    ;;
    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
    ;;
esac
#DEBHELPER#

# Set the installation information if not already present;
# This is done in posttrans for .rpm packages
if [ ! -f "$CONFIG_DIR/install_info" ]; then

    if command -v dpkg >/dev/null 2>&1 && command -v dpkg-query >/dev/null 2>&1; then
        tool=dpkg
        tool_version=dpkg-$(dpkg-query --showformat='${Version}' --show dpkg  | cut -d "." -f 1-3 || echo "unknown")
    else
        tool=unknown
        tool_version=unknown
    fi

    install_info_content="---
install_method:
  tool: $tool
  tool_version: $tool_version
  installer_version: deb_package
"
    echo "$install_info_content" > $CONFIG_DIR/install_info
fi

# Set proper rights to the dd-agent user
chown -R dd-agent:dd-agent ${CONFIG_DIR}
chown -R dd-agent:dd-agent ${LOG_DIR}
chown -R dd-agent:dd-agent ${INSTALL_DIR}

# Make system-probe configs read-only
chmod 0440 ${CONFIG_DIR}/system-probe.yaml.example || true
if [ -f "$CONFIG_DIR/system-probe.yaml" ]; then
    chmod 0440 ${CONFIG_DIR}/system-probe.yaml || true
fi

# Make security-agent config read-only
chmod 0440 ${CONFIG_DIR}/security-agent.yaml.example || true
if [ -f "$CONFIG_DIR/security-agent.yaml" ]; then
    chmod 0440 ${CONFIG_DIR}/security-agent.yaml || true
fi

if [ -d "$CONFIG_DIR/compliance.d" ]; then
    chown -R root:root ${CONFIG_DIR}/compliance.d || true
fi

if [ -d "$CONFIG_DIR/runtime-security.d" ]; then
    chown -R root:root ${CONFIG_DIR}/runtime-security.d || true
fi

# Make the system-probe and security-agent binaries and eBPF programs owned by root
if [ -f "$INSTALL_DIR/embedded/bin/system-probe" ]; then
    chown root:root ${INSTALL_DIR}/embedded/bin/system-probe
fi

if [ -f "$INSTALL_DIR/embedded/bin/security-agent" ]; then
    chown root:root ${INSTALL_DIR}/embedded/bin/security-agent
fi

if [ -d "$INSTALL_DIR/embedded/share/system-probe/ebpf" ]; then
    chown -R root:root ${INSTALL_DIR}/embedded/share/system-probe/ebpf
fi

if [ -d "$INSTALL_DIR/embedded/share/system-probe/java" ]; then
    chown -R root:root ${INSTALL_DIR}/embedded/share/system-probe/java

fi

# Enable and restart the agent service here on Debian platforms
# On RHEL, this is done in the posttrans script
# supports systemd, upstart and sysvinit
echo "Enabling service $SERVICE_NAME"
if command -v systemctl >/dev/null 2>&1; then
    # Force systemd to ignore the sysvinit scripts. Only cosmetic, remove some irrelevant warnings during upgrade
    SYSTEMCTL_SKIP_SYSV=true systemctl enable $SERVICE_NAME || echo "[ WARNING ]\tCannot enable $SERVICE_NAME with systemctl"
    SYSTEMCTL_SKIP_SYSV=true systemctl enable $SERVICE_NAME-process || echo "[ WARNING ]\tCannot enable $SERVICE_NAME-process with systemctl"
    SYSTEMCTL_SKIP_SYSV=true systemctl enable $SERVICE_NAME-trace || echo "[ WARNING ]\tCannot enable $SERVICE_NAME-trace with systemctl"
    SYSTEMCTL_SKIP_SYSV=true systemctl enable $SERVICE_NAME-security || echo "[ WARNING ]\tCannot enable $SERVICE_NAME-security with systemctl"
elif command -v initctl >/dev/null 2>&1; then
    # Nothing to do, this is defined directly in the upstart job file
    :
elif command -v update-rc.d >/dev/null 2>&1; then
    update-rc.d $SERVICE_NAME defaults || echo "[ WARNING ]\tCannot enable $SERVICE_NAME with update-rc.d"
    update-rc.d $SERVICE_NAME-process defaults || echo "[ WARNING ]\tCannot enable $SERVICE_NAME-process with update-rc.d"
    update-rc.d $SERVICE_NAME-trace defaults || echo "[ WARNING ]\tCannot enable $SERVICE_NAME-trace with update-rc.d"
    update-rc.d $SERVICE_NAME-security defaults || echo "[ WARNING ]\tCannot enable $SERVICE_NAME-security with update-rc.d"
else
    echo "[ WARNING ]\tCannot detect a supported init system. The datadog-agent package only provides service files for systemd, upstart and sysvinit."
fi


# TODO: Use a configcheck command on the agent to determine if it's safe to restart,
# and avoid restarting when a check conf is invalid
if [ -f "$CONFIG_DIR/datadog.yaml" ]; then
    echo "(Re)starting $SERVICE_NAME now..."
    if command -v systemctl >/dev/null 2>&1; then
        systemctl restart $SERVICE_NAME || true
    elif command -v initctl >/dev/null 2>&1; then
        initctl start $SERVICE_NAME || initctl restart $SERVICE_NAME || true
    elif command -v service >/dev/null 2>&1; then
        service $SERVICE_NAME restart || true
    else
        echo "[ WARNING ]\tCannot detect a supported init system. The datadog-agent package only provides service files for systemd, upstart and sysvinit."
    fi
else
    # No datadog.yaml file is present. This is probably a clean install made with the
    # step-by-step instructions/an automation tool, and the config file will be added next.
    echo "No datadog.yaml file detected, not starting the agent"
fi

exit 0
